package main

import (
	"context"
	"go.uber.org/zap"
	"net/http"
	"os"
	"os/signal"
	"prj-layout/global"
	"prj-layout/internal/repository/cache"
	"prj-layout/internal/router"
	"syscall"
	"time"

)

// @title          这里写标题
// @version        1.0
// @description    这里写描述信息
// @termsOfService https://swagger.io/terms/

// @contact.name  这里写联系人信息
// @contact.url   https://www.swagger.io/support
// @contact.email support@swagger.io

// @license.name Apache 2.0
// @license.url  https://www.apache.org/licenses/LICENSE-2.0.html

// @host     localhost:8080
// @BasePath /

// @securityDefinitions.apikey ApiKeyAuth
// @in                         header
// @name                       Authorization
// @description                Description for what is this security definition being used
func main() {
	// 初始化应用程序
	global.InitApplication()
	defer func() {
		_ = cache.Rdb.Close()
	}()

	// 设置路由
	r := router.SetupRouter()

	srv := &http.Server{
		Addr:    ":8080",
		Handler: r,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			zap.S().Errorf("listen: %s\n", err)
		}
	}()

	// Wait for interrupt signal to gracefully shutdown the internal with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal)
	// kill (no param) default send syscanll.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall.SIGKILL but can"t be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	zap.L().Info("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		zap.S().Errorf("internal shutdown: %s", err)
	}
	// catching ctx.Done(). timeout of 5 seconds.
	select {
	case <-ctx.Done():
		zap.L().Info("timeout of 5 seconds.")
	}
	zap.L().Info("Server exiting")

}
